package com.springcloudalibaba.apiAsyn.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.springcloudalibaba.bclass.util.LoggerUtil;

import java.text.MessageFormat;

/**
 * @描述: 阿里云 短信 工具类
 * @作者: lixing
 * @日期 2021/6/15 10:29
 * @Param [
 *  regionId: 地域id，从配置文件中读取
 *  accessKeyId: accessKeyId是访问密钥，您可以在控制台上创建和查看
 *  accessSecret: accessKeySecret是访问密钥，您可以在控制台上创建和查看
 *  signName: 阿里云控制台创建，从配置文件中读取
 *  templateCode: 阿里云控制台创建，从配置文件中读取
 *      尊敬的用户您好！您本次登录的验证码为：${code}，请不要告诉他人
 *  phone: 手机号码
 *  param: 短信内容，根据模板中的占位符进行填充。转化成字符串后的格式："{\"code\":\"666666\"}"
 * ]
 */
public class SmsUtil {
    public static Boolean sendSms(String regionId, String accessKeyId, String accessSecret, String signName, String templateCode, String phone, JSONObject param) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        //
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", param.toJSONString());
        try {
            //            {
            //                "Message": "OK",
            //                "RequestId": "F655A8D5-B967-440B-8683-DAD6FF8DE990",
            //                "Code": "OK",
            //                "BizId": "900619746936498440^0"
            //            }
            CommonResponse response = client.getCommonResponse(request);
            String responseStr = response.getData();
            JSONObject jsonObject = JSON.parseObject(responseStr);
            return jsonObject.containsKey("Code") && "OK".equals(jsonObject.getString("Code"));
        } catch (Exception e) {
            LoggerUtil.error(MessageFormat.format("SmsUtil-ServerException: {0}", e.getMessage()));
            return false;
        }
    }
}
